/**
 * 206. 反转链表
 */
public class Solution_206 {
    /**
     * 直接反转即可，注意细节不要断链
     * <p>
     * 时间复杂度：O(N)
     * <p>
     * 空间复杂度：O(1)
     */
    public ListNode reverseList(ListNode head) {
        ListNode pre = null, cur = head;
        while (cur != null) {
            ListNode nextNode = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nextNode;
        }
        return pre;
    }

    public static void main(String[] args) {
        Solution_206 solution = new Solution_206();

        ListNode head = new ListNode();
        ListNode cur = head;
        for (int i = 1; i <= 5; i++) {
            cur.val = i;
            cur.next = new ListNode();
            cur = cur.next;
        }

        // 反转前
        System.out.println("反转前：");
        printListNode(head);

        ListNode ans = solution.reverseList(head);

        // 反转后
        System.out.println("反转后：");
        printListNode(ans);
    }

    public static void printListNode(ListNode head) {
        ListNode cur = head;
        System.out.print("[");
        while (cur != null) {
            System.out.print(cur.val);
            System.out.print(" -> ");
            cur = cur.next;
        }
        System.out.println("null]");
    }
}
